﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace EasyDDD.AdminModule.Application.QueriesSysAdminRole
{
    public record SysAdminRoleGetPageListQuery : IQuery<SysAdminRoleGetPageListQueryResult>
    {
        /// <summary>
        /// 第几页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageIndex { get; set; } = 0;
        /// <summary>
        /// 分页大小
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageSize { get; set; } = 10;
        /// <summary>
        /// 角色标识
        /// </summary>
        public string Code { get; set; } = string.Empty;
        /// <summary>
        /// 角色名称
        /// </summary>
        public string Name { get; set; } = string.Empty;
    }

    public record SysAdminRoleGetPageListQueryResult
    {
        public int CurrentPage { get; set; }
        public int PageSize { get; set; }
        public int Total { get; set; }
        public IList<SysAdminRoleGetPageListQueryResultListItem> list { get; set; } = new List<SysAdminRoleGetPageListQueryResultListItem>();
    }

    [AutoMapperFrom(typeof(Models.ApplicationRole))]
    public record SysAdminRoleGetPageListQueryResultListItem : Models.ApplicationRole
    {
        [JsonIgnore]
        [NotMapped]
        public override bool IsDeleted { get; set; } = default!;
        [JsonIgnore]
        [NotMapped]
        public override Guid TenantId { get; set; } = default!;
    }

    public class SysAdminRoleGetPageListQueryHandler(
        Records.SysAdminRoleRecords records,
        IMapper mapper,
        ILogger<SysAdminRoleGetPageListQueryHandler> logger)
        : IQueryHandler<SysAdminRoleGetPageListQuery, SysAdminRoleGetPageListQueryResult>
    {
        public async Task<SysAdminRoleGetPageListQueryResult> Handle(SysAdminRoleGetPageListQuery request, CancellationToken cancellationToken)
        {
            logger.LogDebug("查询 SysAdminRoleGetPageListQueryHandler");
            var query = records.AsQueryable();
            if (!string.IsNullOrEmpty(request.Code))
            {
                query = query.Where(e => e.Code.Contains(request.Code));
            }
            if (!string.IsNullOrEmpty(request.Name))
            {
                query = query.Where(e => e.Code.Contains(request.Name));
            }
            query = query.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            query = query.OrderBy(e => e.Id);

            var result = new SysAdminRoleGetPageListQueryResult();
            result.Total = await query.CountAsync();
            result.CurrentPage = request.PageIndex;
            result.PageSize = request.PageSize;
            result.list = await mapper.ProjectTo<SysAdminRoleGetPageListQueryResultListItem>(query).ToListAsync(cancellationToken);
            return result;
        }
    }
}
